<?php 
class ioLoginWechat{

    public function __construct(){
    }

    function login($appid, $scope, $callback){  
        $_SESSION ['state'] = md5 ( uniqid ( rand (), true ) ); //CSRF protection
        $params=array(
            'response_type'=>'code',
            'appid'=>$appid,
            'state'=>$_SESSION ['state'],
            'scope'=>$scope,
            'redirect_uri'=>$callback
        );
        $login_url = 'https://open.weixin.qq.com/connect/qrconnect?'.http_build_query($params);
        wp_redirect($login_url, 302);
        exit;
    }
    function callback($appid,$appkey,$code,$state){
        if($_REQUEST ['state'] == $state){ 
            $params=array(
                'grant_type'=>'authorization_code',
                'code'=>$code,
                'appid'=>$appid,
                'secret'=>$appkey
            );
            $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'.http_build_query($params);
            $response = wp_remote_get($token_url);
            $body = wp_remote_retrieve_body($response);
            
            if(preg_match('/\{(.*)\}/', $body, $matches)){
                $msg = json_decode(trim($matches[0]));
                if(isset($msg->errcode)){
                    wp_die($msg->errcode.': '.$msg->errmsg, __('获取微信 Access Token 失败', 'i_theme'), array('response'=>403));
                }
            }else{
                wp_die('微信服务器返回了不正确的响应', __('获取微信 Access Token 失败', 'i_theme'), array('response'=>403));
            }
                
            $_SESSION ['weixin_access_token'] = $msg->access_token;
            $_SESSION ['weixin_open_id'] = $msg->openid; 
        }else{
            echo ("The state does not match. You may be a victim of CSRF.");
            exit;
        }
    }
    function wx_oauth2_get_user_info($access_token, $openid){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        
        $response = wp_remote_get($url);

        $body = wp_remote_retrieve_body($response);

        $msg = null;
        if(preg_match('/\{(.*)\}/', $body, $matches)){
            $msg = json_decode(trim($matches[0]));
            if(isset($msg->errcode)){
                wp_die($msg->errcode.': '.$msg->errmsg, __('获取微信用户信息失败', 'i_theme'), array('response'=>403));
            }
        }else{
            wp_die('微信服务器返回了不正确的响应', __('获取微信用户信息失败', 'i_theme'), array('response'=>403));
        }

        return  $msg ;
    }
    function use_db(){
        global $wpdb;
        $mbt_weixinlogin_backurl = io_get_option('open_login_url')?io_get_option('open_login_url'):get_bloginfo('url');
        if(isset($_SESSION ['weixin_open_id'])){
            if(is_user_logged_in()){
                $userid = wp_get_current_user()->ID;
                $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE wechat_id='".esc_sql($_SESSION['weixin_open_id'])."'");
                if($user_ID && $user_ID != $userid)
                { 
                    wp_die("该账号已经存在，不能绑定到当前账号！", __('绑定失败', 'i_theme'), array('response'=>403));
                }
                $wpdb->query("UPDATE $wpdb->users SET wechat_id = '".esc_sql($_SESSION['weixin_open_id'])."' WHERE ID = '$userid'");
                $uinfo = $this->wx_oauth2_get_user_info($_SESSION ['weixin_access_token'],$_SESSION ['weixin_open_id']); 
                update_user_meta($userid, 'wechat_avatar', $uinfo->headimgurl);
                update_user_meta($userid, 'wechat_name', $uinfo->nickname);
                update_user_meta($userid, 'wechat_openid', esc_sql($_SESSION['weixin_open_id']));
            }
            $user_ID = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE wechat_id='".esc_sql($_SESSION['weixin_open_id'])."'");
            if ($user_ID) {
                wp_set_auth_cookie($user_ID,true,is_ssl());
                wp_redirect($mbt_weixinlogin_backurl);
                if(get_user_meta($user_ID, 'wechat_avatar' )){
                    $uinfo = $this->wx_oauth2_get_user_info($_SESSION ['weixin_access_token'],$_SESSION ['weixin_open_id']); 
                    update_user_meta($user_ID, 'wechat_avatar', $uinfo->headimgurl);
                    update_user_meta($user_ID, 'wechat_name', $uinfo->nickname);
                    update_user_meta($user_ID, 'wechat_openid', esc_sql($_SESSION['weixin_open_id']));
                } 
                exit();
            }else{
                $prename = 'io';
                $extname = rand(1000000,9999998);
                $login_name = $prename.$extname;
                if(username_exists($login_name)){
                    while(username_exists($login_name)){ $extname++; }
                    $login_name = $prename.$extname;
                }
                $pass = wp_generate_password();  
                $uinfo = $this->wx_oauth2_get_user_info($_SESSION ['weixin_access_token'],$_SESSION ['weixin_open_id']); 
                $username = $uinfo->nickname;
                $userdata=array(
                    'user_login' => $login_name,
                    'user_email' => $login_name.'@io.com',
                    'display_name' => $username,
                    'nickname' => $username,
                    'user_pass' => $pass,
                    'role' => get_option('default_role')
                );
                $user_id = wp_insert_user( $userdata );
                if ( is_wp_error( $user_id ) ) {
                    echo $user_id->get_error_message();
                }else{
                    $ff = $wpdb->query("UPDATE $wpdb->users SET wechat_id = '".esc_sql($_SESSION['weixin_open_id'])."' WHERE ID = '$user_id'");
                    update_user_meta($user_id, 'avatar', $uinfo->headimgurl);
                    update_user_meta($user_id, 'wechat_avatar', $uinfo->headimgurl);
                    update_user_meta($user_id, 'wechat_name', $uinfo->nickname);
                    update_user_meta($user_id, 'name_change', 1);
                    update_user_meta($user_id, 'wechat_openid', esc_sql($_SESSION['weixin_open_id']));
                    update_user_meta($user_id, 'avatar_type', 'wechat');
                    wp_set_auth_cookie($user_id,true,is_ssl());
                    wp_redirect($mbt_weixinlogin_backurl);
                }
                exit();
            }
            
        }
    }  
} 
?>
